//
//  HYImageBrowser.m
//  HYSmileiOS
//
//  Created by SMC-MAC on 16/5/18.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "HYImageBrowser.h"
#import "heyou.h"

@interface HYImageBrowser ()  <UIScrollViewDelegate>{
    UIImageView *_mImageView;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) ZFProgressView *progress;

- (IBAction)onButtonClose:(id)sender;
//@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorLoading;

@end

@implementation HYImageBrowser

/**
 *  从XIB加载，调用此函数进行初始化
 */
- (void)awakeFromNib {
    // Initialization code
    // 代码创建UIScrollView
//    UIScrollView *sv = [[UIScrollView alloc] initWithFrame:self.bounds];
//    [self addSubview:sv];
//    self.scrollView = sv;
    
    // 代码设置View 和 UIScrollView的位置和大小
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    self.frame = window.bounds;
    self.scrollView.frame = window.bounds;
    
    self.scrollView.delegate = self;
    self.scrollView.maximumZoomScale = 2.0f;
    self.scrollView.minimumZoomScale = 1.0f;
    WS(ws);
    // 单击图片
    [self.scrollView handleSingleTapWithBlock:^{
        NSLog(@"ScrollView scale = %f", ws.scrollView.zoomScale);
        [ws onButtonClose:nil];
    }];
    // 双击图片
    [self.scrollView handleDoubleTapWithBlock:^{
        if (ws.scrollView.zoomScale < self.scrollView.maximumZoomScale) {
            [ws.scrollView setZoomScale:ws.scrollView.maximumZoomScale animated:YES];
        } else {
            [ws.scrollView setZoomScale:ws.scrollView.minimumZoomScale animated:YES];
        }
    }];
    
    // 代码创建UIImageView
    UIImageView *imageView = [UIImageView new];
    imageView.frame = window.bounds;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.scrollView addSubview:imageView];
    _mImageView = imageView;
    
    // 创建加载进度条
    ZFProgressView *progress = [[ZFProgressView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    progress.backgroundStrokeColor = [UIColor lightGrayColor];
    progress.lineWidth = 4.0f;
    progress.GapWidth = 20.0f;
    progress.hidden = YES;
    progress.center = self.center;
    [self addSubview:progress];
    self.progress = progress;
}

#pragma mark -- ZFProgressView
/**
 *  延迟创建进度条
 *
 *  @return 进度条
 */
//- (ZFProgressView*)getProgress {
//    if (_progress == nil) {
//        ZFProgressView *progress = [[ZFProgressView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
//        [self addSubview:progress];
////        _progress.center = self.center;
//        _progress = progress;
//    }
//    
//    return _progress;
//}

/**
*  全屏显示图片
*/
- (void)show {
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
}

/**
 *  获取图片按照屏幕宽度等比缩放后的高度
 *
 *  @param size 图片的大小
 */
- (CGFloat)getImageViewTargetHeight:(CGSize)size {
    CGFloat height = IMAGE_MIN_HEIGHT;
    
    if (size.width > 0) {
        CGFloat targetWidth = _mImageView.frame.size.width;
        height = size.height / size.width * targetWidth;
    } else {
        NSAssert(NO, @"图片宽度不能<0");
    }
    
    return height;
}

/**
 *  调整UIScrollView的大小，适配大图
 *
 *  @param model 图片模型
 */
- (void)_adjustScrollViewToFitFullImage:(ArticleModel*)model {
    CGFloat imageWidth = model.imageWidth;
    CGFloat imageHeight = model.imageHeight;
    CGSize imageSize = CGSizeMake(imageWidth, imageHeight);
    CGFloat tHeight = [self getImageViewTargetHeight:imageSize];
    if (tHeight > SCREEN_HEIGHT) {
        // 高度超过屏幕，需要顶部对齐屏幕, 让ScrollView滚动
        CGRect tImageFrame = CGRectMake(0, 0, _mImageView.frame.size.width, tHeight);
        _mImageView.frame = tImageFrame;
        self.scrollView.contentSize = tImageFrame.size;
    } else {
        
    }
}

/**
 *  设置在TableView中显示的图片
 *
 *  @param model     图片模型
 *  @param tCell     单元格
 *  @param tableView 列表
 */
- (void)setImage:(ArticleModel*)model cell:(ArticleTableViewCell*)tCell inTable:(UITableView*)tableView {
    // 计算UIImageView的原始位置，可做动画使用
//    UIWindow* window = [UIApplication sharedApplication].keyWindow;
//    // convert rect to cell
//    CGRect rectInCell = [tCell.contentView convertRect:tCell.imageContent.frame toView:tCell];
//    // convert rect to tableview
//    CGRect rectInTableView = [tCell convertRect:rectInCell toView:tableView];
//    // convert rect to window
//    CGRect rectInWindow = [tableView convertRect:rectInTableView toView:window];
//    _mImageView.frame = rectInWindow;
    
    /**
     *  显示大图分两种情况：
        1，有大图
            1.1，大图未缓存，需要下载 - 显示下载进度提示
                首先显示缩略图，下载完成后替换成大图
            1.2，大图有缓存，直接显示
        2，无大图
            直接显示缩略图，把原来的图片移动到屏幕中点
     */
    WS(ws);
    UIImage *placeHolder = tCell.imageContent.image;
    if ([model hasFullImage]) {
        NSString *fURL = model.imageUrl;
        BOOL bExist = [[SDImageCache sharedImageCache] diskImageExistsWithKey:fURL];
        if (bExist) {
            // 测试图片
//            UIImage *tImage = [UIImage smc_imageFromColor:[UIColor redColor] size:imageSize];
            UIImage *tImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:fURL];
            _mImageView.image = tImage;
            
            [ws _adjustScrollViewToFitFullImage:model];
        } else {
            // 没有缓存在本地，需要网络下载
//            _mImageView.image = placeHolder;
            self.progress.hidden = NO;
            NSURL *tURL = [NSURL URLWithString:fURL];
//            [self.progress setProgress:1.0f Animated:YES];
            [_mImageView sd_setImageWithURL:tURL placeholderImage:placeHolder options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                // 更新下载进度
                if (expectedSize > 0) {
                    CGFloat percent = (CGFloat)receivedSize / (CGFloat)expectedSize;
                    [ws.progress setProgress:percent Animated:NO];
                    NSLog(@"(%ld, %ld) - percent === %f", receivedSize, expectedSize, percent);
                }
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                NSLog(@"download thumb image ok");
                // 下载完成，隐藏下载进度条
                ws.progress.hidden = YES;
                if (error) {
                    // 下载出错，显示点击重试按钮
                    NSLog(@"---- complete ---- error = %@", error);
                } else {
                    // 下载成功
                    [ws _adjustScrollViewToFitFullImage:model];
                }
            }];
        }
    } else {
        _mImageView.image = placeHolder;
    }
    
    // 测试代码 - 显示UIImageView的宽高
//    [_mImageView showPlaceHolder];
}



/**
 *  设置图片
 *
 *  @param model 包含图片的模型
 *  @param frame 初始位置
 */
- (void)setImage:(ArticleModel*)model originFrame:(CGRect)frame {
    // http://service.wonbile.com/images/full.JPG
    // http://service.wonbile.com/images/thumb.png
    
    UIImageView *imageView = [UIImageView new];
    imageView.frame = frame;
//    imageView.image = [UIImage imageNamed:@"test1"];
    [self addSubview:imageView];
    
    UIImage *placeHolder = [UIImage imageNamed:@"test1"];
    NSString *sURL = @"http://service.wonbile.com/images/full.JPG";
    NSURL *tURL = [NSURL URLWithString:sURL];
    [imageView sd_setImageWithURL:tURL placeholderImage:placeHolder options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        NSLog(@"receivedSize = %ld, expectedSize = %ld", receivedSize, expectedSize);
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        NSLog(@"imageURL = %@", imageURL);
    }];
    
    // 显示加载提示符
//    self.indicatorLoading.hidden = NO;
//    [self.indicatorLoading startAnimating];
//    [self bringSubviewToFront:self.indicatorLoading];
}

/**
 *  点击关闭按钮
 *
 *  @param sender 按钮
 */
- (IBAction)onButtonClose:(id)sender {
    [self removeFromSuperview];
}

#pragma mark - update constraint
/**
 *  把UIImageView居中
 */
- (void)moveImageViewToCenter {
    UIScrollView *scrollView = self.scrollView;
    CGFloat xcenter = scrollView.center.x , ycenter = scrollView.center.y;
    xcenter = scrollView.contentSize.width > scrollView.frame.size.width?scrollView.contentSize.width/2 : xcenter;
    
    if (self.scrollView.zoomScale > 1.0f) {
        ycenter = scrollView.contentSize.height > scrollView.frame.size.height?scrollView.contentSize.height/2 : ycenter;
        [_mImageView setCenter:CGPointMake(xcenter, ycenter)];
    } else {
        CGPoint tp = _mImageView.center;
        tp.x = xcenter;
        _mImageView.center = tp;
    }
}

#pragma mark -- UIScrollViewDelegate
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _mImageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
//    NSLog(@"bounds = %@, frame = %@, content = %@", NSStringFromCGRect(scrollView.bounds), NSStringFromCGRect(scrollView.frame), NSStringFromCGSize(scrollView.contentSize));
    [self moveImageViewToCenter];
}

@end
